package com.jinzhi.jzweb.controller;


import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.common.pojo.CerUtilsVo;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.service.CertificationBatchService;
import com.jinzhi.jzweb.service.ExaminationBatchService;
import com.jinzhi.jzweb.service.StuSignUpService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ExaminationCostAnalysisUtil;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.mysql.jdbc.StringUtils;
import org.apache.catalina.User;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.service.ExaminationCostService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-04-19 09:36:13 | Long</small>
 */
@Controller
@RequestMapping("/jzweb/examinationCost")
public class ExaminationCostController extends BaseController {
	@Autowired
	private ExaminationCostService examinationCostService;
	@Autowired
	private CertificationBatchService certificationBatchService;
	@Autowired
	private ExaminationBatchService examinationBatchService;
	@Autowired
	private StuSignUpService stuSignUpService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	
	@GetMapping()
	@RequiresPermissions("jzweb:examinationCost:examinationCost")
	String ExaminationCost(Integer year,Model model){
	    model.addAttribute("year",year);
		return "jzweb/examinationCost/examinationCost";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:examinationCost:examinationCost")
	public Result<Page<ExaminationCostDO>> list(ExaminationCostDO examinationCostDTO,String examStartDate,String examEndDate){
		UserDO user = getUser();

		//筛选
		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		if(!getRoleNames().contains("超级用户角色")&&!getRoleNames().contains("市场总监")&&!getRoleNames().contains("财务审核发票")){
			if(getRoleNames().contains("市场一部管理员")){
				wrapper.eq("region_department","市场一部");
			}else if(getRoleNames().contains("市场二部管理员")){
				wrapper.eq("region_department","市场二部");
			}else {
				wrapper.eq("region_user_id",getUserId());
			}
		}
		if(examinationCostDTO.getOrgName()!=null) {
			wrapper.like("org_name", examinationCostDTO.getOrgName());
		}
		if(examinationCostDTO.getState()!=null) {
			wrapper.eq("state", examinationCostDTO.getState());
		}
		if(examinationCostDTO.getProvince()!=null) {
			wrapper.like("province", examinationCostDTO.getProvince());
		}
		if(examinationCostDTO.getYear()!=null) {
			wrapper.eq("year", examinationCostDTO.getYear());
		}
		if(examinationCostDTO.getRegionUserName()!=null){
			wrapper.like("region_user_name",examinationCostDTO.getRegionUserName());
		}

		if(org.apache.commons.lang3.StringUtils.isNotBlank(examStartDate)){
			wrapper.ge("examination_date",examStartDate);
			wrapper.le("examination_date",examEndDate);
		}
		// 查询列表数据
		Page<ExaminationCostDO> page = examinationCostService.selectPage(getPage(ExaminationCostDO.class),wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ExaminationCostDO obj = (ExaminationCostDO) page.getRecords().get(i);
			if(StringUtil.notEmpty(obj.getReturnSchool())){
				obj.setReturnSchool(obj.getReturnSchool());
			}else {
				obj.setReturnSchool(obj.getOrgName());
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}

	@GetMapping("/exportList")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:import")
	public void exportlist( HttpServletRequest request, HttpServletResponse response,ExaminationCostDO examinationCostDTO,String examStartDate,String examEndDate) throws Exception{
		Map map = new HashMap();

		//筛选
		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		System.out.println(getRoleNames());
		if(!getRoleNames().contains("超级用户角色")&&!getRoleNames().contains("市场总监")&&!getRoleNames().contains("财务审核发票")){
			if(getRoleNames().contains("市场一部管理员")){
				wrapper.eq("region_department","市场一部");
			}else if(getRoleNames().contains("市场二部管理员")){
				wrapper.eq("region_department","市场二部");
			}else {
				wrapper.eq("region_user_id",getUserId());
			}
		}
		if(examinationCostDTO.getOrgName()!=null) {
			wrapper.like("org_name", examinationCostDTO.getOrgName());
		}
		if(examinationCostDTO.getState()!=null) {
			wrapper.eq("state", examinationCostDTO.getState());
		}
		if(examinationCostDTO.getProvince()!=null) {
			wrapper.like("province", examinationCostDTO.getProvince());
		}
		if(examinationCostDTO.getYear()!=null) {
			wrapper.eq("year", examinationCostDTO.getYear());
		}
		if(examinationCostDTO.getRegionUserName()!=null){
			wrapper.like("region_user_name",examinationCostDTO.getRegionUserName());
		}

		if(org.apache.commons.lang3.StringUtils.isNotBlank(examStartDate)){
			System.out.println(examStartDate);
			wrapper.ge("examination_date",examStartDate);
			wrapper.le("examination_date",examEndDate);
		}
		List<ExaminationCostDO> examinationCostDOS = examinationCostService.selectList(wrapper);
		if(examinationCostDOS.size()<=0)
			return;
		List<ExaminationCostExportVo> examinationCostExportVoList = new ArrayList<ExaminationCostExportVo>();
		for(ExaminationCostDO c : examinationCostDOS){
			ExaminationCostExportVo exportVo = new ExaminationCostExportVo();
			SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
			exportVo.setExaminationDate(c.getExaminationDate()==null?null:formatter.format(c.getExaminationDate()));
			exportVo.setCommission(c.getCommission()==null?null:c.getCommission().toString());
			exportVo.setLaborWage(c.getLaborWage()==null?null:c.getLaborWage().toString());
			exportVo.setOrgName(c.getOrgName());
			exportVo.setProfile(c.getProfile());
			exportVo.setProvince(c.getProvince());
			exportVo.setReceivables(c.getReceivables()==null?null:c.getReceivables().toString());
			exportVo.setReceived(c.getReceived()==null?null:c.getReceived().toString());
			exportVo.setPlanStuNum(c.getPlanStuNum()==null?null:c.getPlanStuNum().toString());
			exportVo.setReceivedDate(c.getReceivedDate()==null?null:formatter.format(c.getReceivedDate()));
			exportVo.setReturnMoney(c.getReturnMoney()==null?null:c.getReturnMoney().toString());
			exportVo.setRegionUserName(c.getRegionUserName());
			exportVo.setDepartment(c.getRegionDepartment());
			exportVo.setReturnMoneyPersonal(c.getReturnMoneyPersonal()==null?null:c.getReturnMoneyPersonal().toString());
			exportVo.setReturnMoneySchool(c.getReturnMoneySchool()==null?null:c.getReturnMoneySchool().toString());
			exportVo.setPriceStandard(c.getPriceStandard()==null?null:c.getPriceStandard().toString());
			exportVo.setReturnStandard(c.getReturnStandard()==null?null:c.getReturnStandard().toString());
			exportVo.setRemark(c.getRemark());
			exportVo.setYear(c.getYear().toString());
			exportVo.setStuNum(c.getStuNum()==null?null:c.getStuNum().toString());
			switch (c.getState()){
				case 0:exportVo.setState("未开始");break;
				case 1:exportVo.setState("已考试");break;
				case 2:exportVo.setState("已收款");break;
				case 3:exportVo.setState("个人已返款");break;
				case 4:exportVo.setState("学校已返款");break;
				case 5:exportVo.setState("已完成");break;
			}
			examinationCostExportVoList.add(exportVo);
		}
		//System.out.println(examinationCostExportVoList.size());
		EasyPoiUtil.exportExcel(examinationCostExportVoList, "考试费用详情表", "考试费用详情表", ExaminationCostExportVo.class,"考试费用详情表", response);

	}
	
	@GetMapping("/examinationCostAnalysis")
	String examinationCostAnalysis(Model model,ExaminationCostDO examinationCostDTO) throws JSONException {
		if(examinationCostDTO.getYear()!=null)
			model.addAttribute("year",examinationCostDTO.getYear());
		else model.addAttribute("year",0);
	    return "jzweb/examinationCost/examinationCostAnalysis";
	}

	@GetMapping("/getAnalysis")
	@ResponseBody
	@Transactional
	Map getAnalysis(int year) throws JSONException {
		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		if(year!=0)
			wrapper.eq("year",year);
		List<ExaminationCostDO> examinationCostDOS = examinationCostService.selectList(wrapper);
		if(examinationCostDOS.size()>0) {
			Map maps = ExaminationCostAnalysisUtil.schoolMap(examinationCostDOS);
			List<Map> statePie = ExaminationCostAnalysisUtil.statePie(examinationCostDOS);
			Map regionAnalysis = ExaminationCostAnalysisUtil.regionAnalysis(examinationCostDOS);
			maps.put("statePie", statePie);
			maps.putAll(regionAnalysis);
			return maps;
		}
		else
			return null;
	}


	@GetMapping("/add")
	String add(){
		return "jzweb/examinationCost/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:examinationCost:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ExaminationCostDO examinationCost = examinationCostService.selectById(id);
		if(StringUtil.notEmpty(examinationCost.getReturnSchool())){
			examinationCost.setReturnSchool(examinationCost.getReturnSchool());
		}else {
			examinationCost.setReturnSchool(examinationCost.getOrgName());
		}
		model.addAttribute("examinationCost", examinationCost);
	    return "jzweb/examinationCost/edit";
	}
	@GetMapping("/confirmationReturn")
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	String confirmationReturn(Long id,Model model){

		model.addAttribute("id", id);
		return "jzweb/examinationCost/confirmationReturn";
	}

	@Log("提交确认返款")
	@ResponseBody
	@RequestMapping("/confirmationReturnSubmit")
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationReturnSubmit( Long id,String objects){
		int r=0;

			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			if(examinationCostDO.getState()<2){
				return Result.fail("需先确认收款后才能返款");
			}
			if(examinationCostDO.getState()==5){
				return Result.fail("已全部返款，不可重复操作");
			}
			if(objects.split(";;").length==2){
				examinationCostDO.setState(5);
			}else{
				if(objects.equals("0")){
					if(examinationCostDO.getState()==3)
						examinationCostDO.setState(5);
					else examinationCostDO.setState(4);
				}else{
					if(examinationCostDO.getState()==4)
						examinationCostDO.setState(5);
					else examinationCostDO.setState(3);
				}
			}
			examinationCostService.updateById(examinationCostDO);

		return Result.ok();
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:examinationCost:add")
	public Result<String> save( ExaminationCostDO examinationCost){
		examinationCostService.insert(examinationCost);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:examinationCost:edit")
	public Result<String>  update( ExaminationCostDO examinationCost){
		if(examinationCost.getState()>1){
			examinationCost.setStuNum(null);
			examinationCost.setReturnStandard(null);
			examinationCost.setPriceStandard(null);
			if(examinationCost.getReceivables()!=null&&examinationCost.getReturnMoney()!=null&&examinationCost.getLaborWage()!=null)
				examinationCost.setProfit(examinationCost.getReceivables()-examinationCost.getReturnMoney()-examinationCost.getLaborWage());
			boolean update = examinationCostService.updateById(examinationCost);
			return update ? Result.ok() : Result.fail();
		}else{
			ExaminationCostDO ec = examinationCostService.selectById(examinationCost.getId());
			if(ec.getStuNum()==null||ec.getStuNum()<=0) {
				return Result.fail("请确认考试后重试！");
			}
			//如果考生数量、收费标准以及返款标准没有变更，则直接update
			if(examinationCost.getPriceStandard().equals(ec.getPriceStandard())&&examinationCost.getReturnStandard().equals(ec.getReturnStandard())){
				boolean update = examinationCostService.updateById(examinationCost);
				return update ? Result.ok() : Result.fail();
			}
			if(examinationCost.getPriceStandard()==null){
				return Result.fail("收费标准不能为空！");
			}
			if(examinationCost.getReturnStandard()==null){
				return Result.fail("返费标准不能为空！");
			}


			double receivables=ec.getStuNum()*examinationCost.getPriceStandard();
			double returnMoney = ec.getStuNum()*examinationCost.getReturnStandard();
			double laborWage = 0.0;
			if(examinationCost.getLaborWage()==null){
				examinationCost.setLaborWage(laborWage);
			}else{
				laborWage=examinationCost.getLaborWage();
			}
			if(ec.getStuNum()!=null||ec.getStuNum()>0){
				examinationCost.setCommission(ec.getStuNum()*3.0);
			}
			//计算应收款
			examinationCost.setReceivables(receivables);
			//计算应返款
			examinationCost.setReturnMoney(returnMoney);
			//计算学校应返金额
			examinationCost.setReturnMoneySchool(returnMoney*0.3);
			//计算个人应返金额
			examinationCost.setReturnMoneyPersonal(returnMoney*0.7);
			//计算利润
			examinationCost.setProfit(receivables-returnMoney-laborWage);


			boolean update = examinationCostService.updateById(examinationCost);
			return update ? Result.ok() : Result.fail();
		}


	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:remove")
	public Result<String>  remove( Long id){
		examinationCostService.deleteById(id);
        return Result.ok();
	}

	@Log("预收")
	@PostMapping( "/confirmationAdvance")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationAdvance(Long id,Double advance){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		//确认收款
			//如何未输入实收金额，则默认实收金额=应收金额
			if(advance==null||advance<=0){
				return Result.fail("请填写预收金额！");
			}
			examinationCostDO.setAdvanceDate(new Date());
			examinationCostDO.setAdvance(advance);
			examinationCostService.updateById(examinationCostDO);
			return Result.ok();
	}

	@Log("确认收款")
	@PostMapping( "/confirmationReceivable")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationReceivable(Long id,Double received){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			//确认收款
			if (examinationCostDO.getState() == 1||examinationCostDO.getState() == 2) {
				//如何未输入实收金额，则默认实收金额=应收金额
				if(received==-1){
					examinationCostDO.setState(2);
					examinationCostDO.setReceivedDate(new Date());
					examinationCostDO.setReceived(examinationCostDO.getReceivables());
				}else {
					examinationCostDO.setState(2);
					examinationCostDO.setReceivedDate(new Date());
					examinationCostDO.setReceived(received);
				}
				examinationCostService.updateById(examinationCostDO);
				return Result.ok();
			}else{
				return Result.fail("未考试或已返款的数据无法再确认收款");
			}
	}

	@Log("批量确认收款")
	@PostMapping( "/confirmationReceivables")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationReceivables(@RequestParam("ids[]") Long[] ids){
		//批量确认收款，则默认实收金额=应收金额
		int r=0;
		for(Long id : ids) {
			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			//确认收款
			if (examinationCostDO.getState() == 1||examinationCostDO.getState() == 2) {
				r++;
				examinationCostDO.setState(2);
				examinationCostDO.setReceivedDate(new Date());
				examinationCostDO.setReceived(examinationCostDO.getReceivables());
			}
			examinationCostService.updateById(examinationCostDO);
		}
		if(r==ids.length)
			return Result.ok();
		else{
			return Result.fail("部分确认收款失败，可能已确认收款或未考试");
		}
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		examinationCostService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	@Log("计算费用")
	@PostMapping( "/calculate")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:calculate")
	public Result<String>  calculate(Long id,Integer stuNum,Date start){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		if(examinationCostDO.getState()>1){
			return Result.fail("操作失败，已确认收费后的数据无法再重新计算费用！");
		}
		examinationCostDO.setState(1);
		examinationCostDO.setStuNum(stuNum);
		double receivables=stuNum*examinationCostDO.getPriceStandard();
		double returnMoney = stuNum*examinationCostDO.getReturnStandard();
		double laborWage = 0.0;
		if(examinationCostDO.getLaborWage()==null){
			examinationCostDO.setLaborWage(laborWage);
		}else{
			laborWage=examinationCostDO.getLaborWage();
		}
		examinationCostDO.setExaminationDate(start);
		//计算应收款
		examinationCostDO.setReceivables(receivables);
		//计算应返款
		examinationCostDO.setReturnMoney(returnMoney);
		//计算学校应返金额
		examinationCostDO.setReturnMoneySchool(returnMoney*0.3);
		//计算个人应返金额
		examinationCostDO.setReturnMoneyPersonal(returnMoney*0.7);
		//计算提成
		examinationCostDO.setCommission(stuNum*3.0);
		//计算利润
		examinationCostDO.setProfit(receivables-returnMoney-laborWage);
		//如果预收款大于等于应收款，则直接更改状态为已收款
		if(examinationCostDO.getAdvance()!=null&&examinationCostDO.getAdvance()>=receivables){
			examinationCostDO.setState(2);
		}
		examinationCostService.updateById(examinationCostDO);
		return Result.ok("操作成功");
	}

	@Log("确认考试批次及人数")
	@PostMapping( "/selBatchStuNum")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:calculate")
	public Result<List<ExaminationBatchDO>>  selBatchStuNum(Long id){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		if(examinationCostDO.getState()>1){
				return Result.fail("操作失败，已确认收费后的数据无法再确认考试！");
			}

		Wrapper<ExaminationBatchDO> wrapper = new EntityWrapper<ExaminationBatchDO>().orderBy("start_time",true);
		wrapper.like("name",examinationCostDO.getOrgName());
		if(examinationCostDO.getProfile().contains("初级")){
			wrapper.like("name","初级");
		}
		if(examinationCostDO.getProfile().contains("中级")){
			wrapper.like("name","中级");
		}
		if(examinationCostDO.getProfile().contains("高级")){
			wrapper.like("name","高级");
		}
		wrapper.like("name",examinationCostDO.getOrgName());
		wrapper.notLike("name","测试");
		wrapper.notLike("name","师资");
		wrapper.notLike("name","考务技术员");
		wrapper.gt("start_time",examinationCostDO.getYear()+"-02-10");
		wrapper.le("start_time",(examinationCostDO.getYear()+1)+"-02-10");
		List<ExaminationBatchDO> examinationBatchDOList = examinationBatchService.selectList(wrapper);
		if(examinationBatchDOList.size()<=0){
			return Result.fail("未查询到相关考试批次，请核实后再确认考试！");
		}
		for(int i=0;i<examinationBatchDOList.size();i++){
			Wrapper<StuSignUpDO> stuSignUpWrapper = new EntityWrapper<>();
			stuSignUpWrapper.eq("cbatch_id",examinationBatchDOList.get(i).getId());
			stuSignUpWrapper.notLike("name","0");
			stuSignUpWrapper.notLike("name","cs");
			stuSignUpWrapper.notLike("name","测试");
			List<StuSignUpDO> stuSignUpDOS = stuSignUpService.selectList(stuSignUpWrapper);
			examinationBatchDOList.get(i).setStuNum(stuSignUpDOS.size());
		}

//		int r=0;
//			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
//			if(examinationCostDO.getState()>1){
//				return Result.fail("操作失败，已确认收费后的数据无法再计算费用！");
//			}
//			r++;
//			examinationCostDO.setState(1);
//
//			examinationCostDO.setStuNum(stuNum);
//			double receivables=stuNum*examinationCostDO.getPriceStandard();
//			double returnMoney = stuNum*examinationCostDO.getReturnStandard();
//			double laborWage = 0.0;
//			if(examinationCostDO.getLaborWage()==null){
//				examinationCostDO.setLaborWage(laborWage);
//			}else{
//				laborWage=examinationCostDO.getLaborWage();
//			}
//
//			//计算应收款
//			examinationCostDO.setReceivables(receivables);
//			//计算应返款
//			examinationCostDO.setReturnMoney(returnMoney);
//			//计算学校应返金额
//			examinationCostDO.setReturnMoneySchool(returnMoney*0.3);
//			//计算个人应返金额
//			examinationCostDO.setReturnMoneyPersonal(returnMoney*0.7);
//			//计算提成
//			examinationCostDO.setCommission(stuNum*3.0);
//			//计算利润
//			examinationCostDO.setProfit(receivables-returnMoney-laborWage);
//			//如果预收款大于等于应收款，则直接更改状态为已收款
//			if(examinationCostDO.getAdvance()!=null&&examinationCostDO.getAdvance()>=receivables){
//				examinationCostDO.setState(2);
//			}
//			examinationCostService.updateById(examinationCostDO);

		return Result.ok(examinationBatchDOList);
	}


	@Log("批量核对人数")
	@PostMapping( "/checkStuNum")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:checkStuNum")
	public Result<String>  checkStuNum(@RequestParam("ids[]") Long[] ids){
		String msg = "";
		for(Long id : ids) {
			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			if(examinationCostDO.getState()!=1){
				msg = "部分数据核对失败，只能核对状态为“已计算”的数据";
				continue;
			}
			examinationCostDO.setState(2);
			examinationCostService.updateById(examinationCostDO);
		}
		return Result.ok(msg);
	}

	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@RequiresPermissions("jzweb:examinationCost:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<ExaminationCostImportVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "考试费用详情导入模板", "考试费用详情导入模板", ExaminationCostImportVo.class, "考试费用详情导入模板", response);
	}

	/**
	 * 考试费用详情表导入
	 *
	 * @param file excel文件,cType:专家类型（0师资，1考评员）
	 */
	@Log("考试费用详情表导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:import")
	public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<ExaminationCostImportVo> list = EasyPoiUtil.importExcel(file, 1, 1, ExaminationCostImportVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该表第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<ExaminationCostDO> examCostList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		List<ExaminationCostImportVo> cerUtilsVos = new ArrayList<>();

		for (int i = 0; i < list.size(); i++) {
			StringBuilder sb = new StringBuilder();
			if(StringUtils.isNullOrEmpty(list.get(i).getRegionUserName())){
				sb.append("第" + (i + startRow) + "行区域负责人姓名未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getMobile())){
				sb.append("第" + (i + startRow) + "行区域负责人手机号未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getOrgName())){
				sb.append("第" + (i + startRow) + "行学校名称未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getProvince())){
				sb.append("第" + (i + startRow) + "行省份未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getDepartment())){
				sb.append("第" + (i + startRow) + "行所属部门未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getProfile())){
				sb.append("第" + (i + startRow) + "行证书及等级未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getYear())){
				sb.append("第" + (i + startRow) + "行年份未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getPlanStuNum())){
				sb.append("第" + (i + startRow) + "行计划考试人数未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getPriceStandard())){
				sb.append("第" + (i + startRow) + "行收费标准未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getReturnStandard())){
				sb.append("第" + (i + startRow) + "行返费标准未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getState())){
				sb.append("第" + (i + startRow) + "行状态未填写，请完善！" + ";");
			}else if(!IdCardUtil.isNumeric(list.get(i).getYear())){
				sb.append("第" + (i + startRow) + "行年份格式错误，只能填数字！" + ";");
			}else if(!IdCardUtil.isNumeric(list.get(i).getPlanStuNum())){
				sb.append("第" + (i + startRow) + "行计划考试人数格式错误，只能填数字！" + ";");
			}else if(!StringUtils.isNullOrEmpty(list.get(i).getStuNum())&&!IdCardUtil.isNumeric(list.get(i).getStuNum())){
				sb.append("第" + (i + startRow) + "行实际人数格式错误，只能填数字！" + ";");
			}else if(!IdCardUtil.isNumericDou(list.get(i).getPriceStandard())){
				sb.append("第" + (i + startRow) + "行收费标准格式错误，只能填数值！" + ";");
			}else if(!IdCardUtil.isNumericDou(list.get(i).getReturnStandard())){
				sb.append("第" + (i + startRow) + "行返费标准格式错误，只能填数值！" + ";");
			}else{
				if (!ValidUtils.isMobile(list.get(i).getMobile())) {
					sb.append("第" + (i + startRow) + "行手机号码格式错误，请修改！" + ";");
				}else{
					if(!DepartmentTest(list.get(i).getDepartment())){
						sb.append("第" + (i + startRow) + "行所属部门填写错误，请修改！" + ";");
					}else {
						UserDO user = userService.findOneByKv("mobile", list.get(i).getMobile());
						//创建用户
						if (user == null) {
							user = new UserDO();
							user.setName(list.get(i).getRegionUserName());
							user.setUsername(list.get(i).getRegionUserName());
							String password = "000000";
							String salt = UUIDUtils.get();
							String encodePasswd = PasswdUtils.get(password, salt);
							user.setSalt(salt);
							user.setPassword(encodePasswd);
							user.setMobile(list.get(i).getMobile());
							user.setType(0);//默认个人会员
							user.setMoney(BigDecimal.valueOf(0.0));//默认0元
							user.setGmtCreate(new Date());
							user.setGmtModified(user.getGmtCreate());
							user.setStatus(1);//默认正常
							user.setSex(0L);//性别，默认未知
							userService.insert(user);
							//配置角色
							RoleDO roleDO = roleService.findOneByKv("roleName",list.get(i).getDepartment());
							UserRoleDO userRoleDO = new UserRoleDO();
							userRoleDO.setRoleId(roleDO.getId());
							userRoleDO.setUserId(user.getId());
							userRoleService.insert(userRoleDO);
						}else{
							//判断用户表中的姓名与该表中的姓名是否一致，不一致则按照该表修改用户表
							if(user.getName()==null||!user.getName().equals(list.get(i).getRegionUserName())){
								user.setName(list.get(i).getRegionUserName());
								userService.updateById(user);
							}
							//判断该用户是否已经配置相关角色
							RoleDO roleDO = roleService.findOneByKv("roleName",list.get(i).getDepartment());
							UserRoleDO userRoleDO = userRoleService.findOneByKv("roleId",roleDO.getId(),"userId",user.getId());
							if(userRoleDO==null){
								userRoleDO = new UserRoleDO();
								userRoleDO.setRoleId(roleDO.getId());
								userRoleDO.setUserId(user.getId());
								userRoleService.insert(userRoleDO);
							}
						}

						//
						Double priceStandard=Double.parseDouble(list.get(i).getPriceStandard());
						Double returnStandard = Double.parseDouble(list.get(i).getReturnStandard());
						ExaminationCostDO examinationCostDO = new ExaminationCostDO();
						examinationCostDO.setOrgName(list.get(i).getOrgName());
						examinationCostDO.setYear(Integer.parseInt(list.get(i).getYear()));
						examinationCostDO.setProvince(list.get(i).getProvince());
						examinationCostDO.setProfile(list.get(i).getProfile());
						examinationCostDO.setPlanStuNum(Integer.parseInt(list.get(i).getPlanStuNum()));
						examinationCostDO.setPriceStandard(priceStandard);
						examinationCostDO.setReturnStandard(returnStandard);
						examinationCostDO.setRegionUserId(user.getId());
						examinationCostDO.setRegionUserName(user.getName());
						examinationCostDO.setRegionDepartment(list.get(i).getDepartment());
						if(!StringUtils.isNullOrEmpty(list.get(i).getLaborWage())){
							examinationCostDO.setLaborWage(Double.parseDouble(list.get(i).getLaborWage()));
						}
						if(!StringUtils.isNullOrEmpty(list.get(i).getLaborWage())){
							examinationCostDO.setLaborWage(Double.parseDouble(list.get(i).getLaborWage()));
						}
						if(list.get(i).getExaminationDate()!= null){
							examinationCostDO.setExaminationDate(list.get(i).getExaminationDate());
						}

						if(!StringUtils.isNullOrEmpty(list.get(i).getStuNum())){
							int stuNum=Integer.parseInt(list.get(i).getStuNum());
							examinationCostDO.setStuNum(stuNum);
							examinationCostDO.setReceivables(stuNum*priceStandard);
							examinationCostDO.setReturnMoney(stuNum*returnStandard);
							examinationCostDO.setReturnMoneyPersonal((stuNum*returnStandard)*0.7);
							examinationCostDO.setReturnMoneySchool((stuNum*returnStandard)*0.3);
							examinationCostDO.setCommission(stuNum*3.0);
						}
						if(list.get(i).getState().equals("未开始"))
							examinationCostDO.setState(0);
						else if(!list.get(i).getState().equals("未开始")&&StringUtils.isNullOrEmpty(list.get(i).getStuNum())){
							sb.append("第" + (i + startRow) + "行数据已考试，但实际考试人数未填写，请完善！" + ";");
							continue;
						}
						else if(list.get(i).getState().equals("已考试")){
							examinationCostDO.setState(1);
						}
						else if(list.get(i).getState().equals("已回款")){
							if(StringUtils.isNullOrEmpty(list.get(i).getReceived())){
								examinationCostDO.setReceived(examinationCostDO.getReceivables());
							}else{
								examinationCostDO.setReceived(Double.parseDouble(list.get(i).getReceived()));
							}
							examinationCostDO.setState(2);
						}
						else if(list.get(i).getState().equals("个人已返款"))
							examinationCostDO.setState(3);
						else if(list.get(i).getState().equals("学校已返款"))
							examinationCostDO.setState(4);
						else if(list.get(i).getState().equals("已完成"))
							examinationCostDO.setState(5);
						else{
							sb.append("第" + (i + startRow) + "行状态填写错误，请修改！" + ";");
							continue;
						}
						examCostList.add(examinationCostDO);
					}
				}
			}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			}
		}
		if (list1.size() == 0) {
			examinationCostService.insertBatch(examCostList);
			return Result.ok("成功导入" + list.size() + "条数据");
		}else{
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("trainingCertificates" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}

	private boolean DepartmentTest(String department){
		if(department.equals("市场一部")||department.equals("市场二部")||department.equals("市场一部管理员")||department.equals("市场二部管理员"))
			return true;
		return false;
	}

	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:import")
	public void importError(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考试费用详情导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("trainingCertificates" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}
}
